package a07_二叉树;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;

/**
 * <p>
 * a13_二叉树的所有路径复习0
 * </p>
 *
 * @author flyduck
 * @since 2024/12/30
 */
public class a13_二叉树的所有路径复习0 {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> resultList = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        traversal(root, resultList, stack);
        return resultList;
    }

    public void traversal(TreeNode currentNode,List<String> resultList, Stack<TreeNode> path){
        if (currentNode == null) {
            return;
        }

        path.add(currentNode);

        if (currentNode.left == null && currentNode.right == null) {
            String collect = new ArrayList<>(path).stream().map(treeNode -> String.valueOf(treeNode.val)).collect(Collectors.joining("->"));
            resultList.add(collect);
            return;
        }

        traversal(currentNode.left, resultList, path);
        if(currentNode.left != null){
            path.pop();
        }
        traversal(currentNode.right, resultList, path);
        if(currentNode.right != null){
            path.pop();
        }
    }
}
